window.onload = function () {
    const oUl = document.querySelector('ul');
    const oInput = document.querySelector('input');
    const oButton = document.querySelector('button');
    const ws = new WebSocket('ws:localhost:5500');
    let username = ''

    const init = () => {
        bindEvent()
    }

    function bindEvent () {
        oButton.addEventListener('click',handleBTn,false)
        ws.addEventListener('open',handleOpen,false)
        ws.addEventListener('close',handleClose,false)
        ws.addEventListener('error',handleError,false)
        ws.addEventListener('message',handleMsg,false)
    }

    function handleBTn(){
        const msg = oInput.value
        ws.send(JSON.stringify(
            {
                username,
                time:new Date().getTime(),
                msg
            }
        ))
        oInput.value = ''
    }

    function handleOpen(e){
        username = localStorage.getItem('username')
        if( !username ){
            location.href = 'entry.html'
            return
        }
    }

    function handleClose(e){
        console.log("close");
    }

    function handleError(e){
        console.log("error");
    }

    function handleMsg(e){
        const li = JSON.parse(e.data)
        oUl.appendChild(createMsg(li))
    }

    function createMsg (itemLi) {
        const { username , time ,msg } = itemLi
        const oItem = document.createElement('li')

        oItem.innerHTML = `
        <p>
            <span>${username}</span>
            <span>------------</span>
            <span>${time}</span>
            <span>------------</span>
            <span>${msg}</span>
        </p>
        
        `
        return oItem
    }

    init()
    
    
}